package com.ruoyi.web.controller.admin;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.CullenUtils;
import com.ruoyi.module.domain.Account;
import com.ruoyi.module.service.IAccountService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.module.domain.FundDetails;
import com.ruoyi.module.service.IFundDetailsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资金明细Controller
 *
 * @author fubojin
 * @date 2025-01-10
 */
@RestController
@RequestMapping("/admin/details")
public class FundDetailsController extends BaseController {
    @Autowired
    private IFundDetailsService fundDetailsService;

    @Autowired
    private IAccountService accountService;

    /**
     * 查询资金明细列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FundDetails fundDetails) {
        startPage();
        List<FundDetails> list = fundDetailsService.selectFundDetailsList(fundDetails);
        return getDataTable(list);
    }

    /**
     * 查询借款模块资金明细列表
     */
    @GetMapping("/loanList")
    public TableDataInfo loanList(FundDetails fundDetails) {
        startPage();
        List<FundDetails> list = fundDetailsService.selectFundDetailsLoanList(fundDetails);
        return getDataTable(list);
    }

    /**
     * 导出资金明细列表
     */
    @Log(title = "资金明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FundDetails fundDetails) {
        List<FundDetails> list = fundDetailsService.selectFundDetailsList(fundDetails);
        ExcelUtil<FundDetails> util = new ExcelUtil<FundDetails>(FundDetails.class);
        util.exportExcel(response, list, "资金明细数据");
    }

    /**
     * 获取资金明细详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(fundDetailsService.selectFundDetailsById(id));
    }

    /**
     * 新增资金明细
     */
    @Log(title = "资金明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FundDetails fundDetails) {
        return toAjax(fundDetailsService.insertFundDetails(fundDetails));
    }

    /**
     * 修改资金明细
     */
    @Log(title = "资金明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FundDetails fundDetails) {
        return toAjax(fundDetailsService.updateFundDetails(fundDetails));
    }

    /**
     * 总后台给经销商借款
     */
    @Log(title = "资金明细", businessType = BusinessType.UPDATE)
    @PutMapping("/updateLoan")
    public AjaxResult updateLoan(@RequestParam String orderNo) {
        return toAjax(fundDetailsService.updateLoan(orderNo));
    }

    /**
     * 还款
     */
    @Log(title = "资金明细", businessType = BusinessType.UPDATE)
    @PutMapping("/updateLoanMoney")
    public AjaxResult updateLoanMoney(@RequestBody FundDetails fundDetails) {
        FundDetails selectFundDetails = fundDetailsService.selectFundDetailsById(fundDetails.getId());
        Account account = accountService.selectAccountByUserId(selectFundDetails.getUserId());

        BigDecimal accountBalance = account.getAccountBalance();//账号余额
        BigDecimal creditGold = account.getCreditGold();//信誉金
        BigDecimal loanMoney = fundDetails.getLoanMoney();//还款金额
        BigDecimal loanMoney1 = selectFundDetails.getLoanMoney();//已还款金额部分
        CullenUtils.validateDataThrowException(loanMoney.compareTo(creditGold.add(accountBalance)) > 0, "还款金额大于账户余额(" + loanMoney1.add(loanMoney) + ")！");

        if (loanMoney1.equals(new BigDecimal("0"))) {
            selectFundDetails.setLoanMoney(loanMoney);
        } else {
            selectFundDetails.setLoanMoney(loanMoney1.add(loanMoney));
        }
        if (selectFundDetails.getVariableAmount().equals(selectFundDetails.getLoanMoney())) {
            selectFundDetails.setLoanType(5);
        } else {
            selectFundDetails.setLoanType(4);
        }
        selectFundDetails.setRemark(fundDetails.getRemark());
        fundDetailsService.updateFundDetails(selectFundDetails);//更改还款类型和金额


        selectFundDetails.setId(null);
        selectFundDetails.setLoanType(6);
        selectFundDetails.setLoanMoney(loanMoney);
        int i = fundDetailsService.insertFundDetails(selectFundDetails);

        //更改经销商余额
        if (accountBalance.compareTo(loanMoney) >= 0 ) {
            account.setAccountBalance(accountBalance.subtract(loanMoney));
        }else if (accountBalance.compareTo(loanMoney) < 0){
            account.setAccountBalance(new BigDecimal("0"));
            //扣除信用金 = 信用金 - （还款金额 - 员工余额）
            account.setCreditGold(creditGold.subtract(loanMoney.subtract(accountBalance)));
        }
            accountService.updateAccount(account);

        return toAjax(i);
    }

    /**
     * 删除资金明细
     */
    @Log(title = "资金明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fundDetailsService.deleteFundDetailsByIds(ids));
    }
}
